/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.scriptutils

import cool.taomu.software.fig.objectpool.ObjectPoolFactory
import groovy.lang.GroovyClassLoader
import groovy.lang.GroovyClassLoader.InnerLoader
import groovy.lang.GroovyCodeSource
import java.io.Serializable
import org.codehaus.groovy.runtime.IOGroovyMethods
import org.slf4j.LoggerFactory

class GroovyScript implements IFigScript, AutoCloseable {
	val static LOG = LoggerFactory.getLogger(GroovyScript)
	Class<?> groovyClass = null;

	new(String path) {
		LOG.info(String.format("加载脚本:%s",path))
		var scriptInput = Thread.currentThread.contextClassLoader.getResourceAsStream(path)
		var gl = new GroovyClassLoader(Thread.currentThread.contextClassLoader);
		var il = new InnerLoader(gl);
		var scriptText = IOGroovyMethods.getText(scriptInput);
		var c = new GroovyCodeSource(scriptText, path, "/groovy/script");
		groovyClass = il.parseClass(c);
		il.close();
		ObjectPoolFactory.perparePool(groovyClass)
	}

	override <K, T extends Serializable> K invoke(String name, T value) {
		try(var pool = ObjectPoolFactory.borrowObject(groovyClass)) {
			var method = groovyClass.getMethod(name, value.class)
			method.accessible = true
			var result = method.invoke(pool.instance, value)
			return result !== null ? result as K 
		}
	}
	
	def static void main(String[] args){
		var String name = null
		println(name !== null ? name as Object)
	}

	override close() throws Exception {
	}

}
